<?php
/**
 * 3-4岁专区认知模块编辑页面
 */
require_once '../../../admin/check_session.php';
require_once '../../../includes/config.php';
require_once '../includes/CognitiveManager34.php';

// 创建认知管理器实例
$cognitiveManager = new CognitiveManager34();

// 初始化模块数据
$module = [
    'module_id' => 0,
    'module_name' => '',
    'module_key' => '',
    'description' => '',
    'icon' => '🎨',
    'display_order' => 0,
    'background_color' => 'pink',
    'border_color' => 'pink',
    'is_active' => 1
];

// 检查是否是编辑现有模块
$isEditing = false;
if (isset($_GET['id'])) {
    $moduleId = (int)$_GET['id'];
    $existingModule = $cognitiveManager->getModuleById($moduleId);
    
    if ($existingModule) {
        $module = $existingModule;
        $isEditing = true;
    }
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 收集表单数据
    $moduleData = [
        'module_name' => $_POST['module_name'],
        'module_key' => $_POST['module_key'],
        'description' => $_POST['description'],
        'icon' => $_POST['icon'],
        'display_order' => (int)$_POST['display_order'],
        'background_color' => $_POST['background_color'],
        'border_color' => $_POST['border_color'],
        'is_active' => isset($_POST['is_active']) ? 1 : 0,
        'age_group' => '3-4' // 固定为3-4岁年龄段
    ];
    
    // 验证必填字段
    $errors = [];
    if (empty($moduleData['module_name'])) {
        $errors[] = "模块名称不能为空";
    }
    
    if (empty($moduleData['module_key'])) {
        $errors[] = "模块Key不能为空";
    } else {
        // 检查module_key格式（只允许字母、数字和下划线）
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $moduleData['module_key'])) {
            $errors[] = "模块Key只能包含字母、数字和下划线";
        }
        
        // 检查重复的module_key
        if (!$isEditing || $moduleData['module_key'] !== $module['module_key']) {
            $existingModule = $cognitiveManager->moduleManager->getModuleByKey($moduleData['module_key'], '3-4');
            if ($existingModule) {
                $errors[] = "模块Key已存在，请使用其他标识符";
            }
        }
    }
    
    // 如果没有错误，保存数据
    if (empty($errors)) {
        if ($isEditing) {
            // 更新现有模块
            $result = $cognitiveManager->updateModule($moduleId, $moduleData);
            
            if ($result) {
                $successMessage = "认知模块已成功更新";
                // 重新加载模块数据
                $module = $cognitiveManager->getModuleById($moduleId);
            } else {
                $errorMessage = "更新认知模块时出错";
            }
        } else {
            // 添加新模块
            $newModuleId = $cognitiveManager->addModule($moduleData);
            
            if ($newModuleId) {
                // 重定向到模块列表页面
                header("Location: cognitive_modules.php?success=1");
                exit;
            } else {
                $errorMessage = "添加认知模块时出错";
            }
        }
    }
}

// 添加页面标题
$pageTitle = $isEditing ? "编辑认知模块" : "添加认知模块";
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - KidsMind管理后台</title>
    <!-- 引入管理后台通用样式 -->
    <link rel="stylesheet" href="/admin/css/admin.css">
    <link rel="stylesheet" href="/admin/css/bootstrap.min.css">
    <link rel="stylesheet" href="/admin/css/fontawesome.min.css">
    <!-- 3-4岁专用样式 -->
    <style>
        .form-card {
            border-radius: 15px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            background-color: #fff;
            padding: 30px;
            margin-bottom: 30px;
        }
        .preview-card {
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        .preview-header {
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        .preview-icon {
            font-size: 2rem;
            margin-right: 10px;
        }
        .color-preview {
            width: 30px;
            height: 30px;
            display: inline-block;
            border-radius: 5px;
            margin-right: 10px;
            border: 1px solid #ddd;
        }
        /* 马卡龙色系配色 */
        .bg-pastel-pink { background-color: #FFD6E0; }
        .bg-pastel-blue { background-color: #D6E5FF; }
        .bg-pastel-green { background-color: #D6FFE1; }
        .bg-pastel-yellow { background-color: #FFEFD6; }
        .bg-pastel-purple { background-color: #E9D6FF; }
        .color-option {
            display: inline-block;
            width: 30px;
            height: 30px;
            margin: 0 5px;
            border-radius: 5px;
            cursor: pointer;
            border: 2px solid transparent;
        }
        .color-option.selected {
            border-color: #333;
        }
        .color-option:hover {
            transform: scale(1.1);
        }
        .emoji-picker {
            display: flex;
            flex-wrap: wrap;
            margin-top: 10px;
            gap: 5px;
        }
        .emoji-option {
            font-size: 1.5rem;
            padding: 5px;
            cursor: pointer;
            border-radius: 5px;
            border: 1px solid transparent;
        }
        .emoji-option:hover, .emoji-option.selected {
            background-color: #f0f0f0;
            border-color: #ccc;
        }
    </style>
</head>
<body>
    <?php include '../../../admin/includes/header.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <?php include '../../../admin/includes/sidebar.php'; ?>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2"><?php echo $pageTitle; ?></h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <a href="cognitive_modules.php" class="btn btn-sm btn-outline-secondary">返回模块列表</a>
                        </div>
                    </div>
                </div>
                
                <?php if (isset($successMessage)): ?>
                <div class="alert alert-success" role="alert">
                    <?php echo $successMessage; ?>
                </div>
                <?php endif; ?>
                
                <?php if (isset($errorMessage)): ?>
                <div class="alert alert-danger" role="alert">
                    <?php echo $errorMessage; ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger" role="alert">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo $error; ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
                
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-card">
                            <form method="post" action="">
                                <div class="mb-3">
                                    <label for="module_name" class="form-label">模块名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="module_name" name="module_name" 
                                           value="<?php echo htmlspecialchars($module['module_name']); ?>" required>
                                    <div class="form-text">例如："颜色认知"、"形状认知"等</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="module_key" class="form-label">模块Key <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="module_key" name="module_key" 
                                           value="<?php echo htmlspecialchars($module['module_key']); ?>" required>
                                    <div class="form-text">用于URL和标识的简短关键字，如"colors"、"shapes"（只能包含字母、数字和下划线）</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="description" class="form-label">模块描述</label>
                                    <textarea class="form-control" id="description" name="description" rows="4"><?php echo htmlspecialchars($module['description']); ?></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">模块图标</label>
                                    <input type="hidden" id="icon" name="icon" value="<?php echo htmlspecialchars($module['icon']); ?>">
                                    <div class="d-flex align-items-center mb-2">
                                        <span id="selected-icon" class="display-4 me-3"><?php echo $module['icon']; ?></span>
                                        <button type="button" class="btn btn-outline-secondary" id="toggle-emoji-picker">
                                            选择图标
                                        </button>
                                    </div>
                                    <div class="emoji-picker" id="emoji-picker" style="display: none;">
                                        <?php
                                        $commonEmojis = ['🎨', '🔍', '🧩', '🎯', '🎭', '🎪', '🎡', '🎢', '🎠', '🎮', 
                                                        '🧸', '🪁', '🎲', '📚', '📝', '🔢', '🎵', '🎶', '🎻', '🎹'];
                                        foreach ($commonEmojis as $emoji) {
                                            $selected = ($emoji === $module['icon']) ? 'selected' : '';
                                            echo '<span class="emoji-option ' . $selected . '" data-emoji="' . $emoji . '">' . $emoji . '</span>';
                                        }
                                        ?>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="display_order" class="form-label">显示顺序</label>
                                    <input type="number" class="form-control" id="display_order" name="display_order" 
                                           value="<?php echo (int)$module['display_order']; ?>" min="0">
                                    <div class="form-text">数字越小，显示越靠前</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">背景颜色</label>
                                    <input type="hidden" id="background_color" name="background_color" 
                                           value="<?php echo htmlspecialchars($module['background_color']); ?>">
                                    <div class="d-flex align-items-center mb-2">
                                        <div id="background-preview" class="color-preview" 
                                             style="background-color: <?php echo getColorCode($module['background_color']); ?>"></div>
                                        <span id="background-name"><?php echo getColorName($module['background_color']); ?></span>
                                    </div>
                                    <div>
                                        <span class="color-option <?php echo ($module['background_color'] === 'pink') ? 'selected' : ''; ?>" 
                                              data-color="pink" data-name="粉红" style="background-color: #FFD6E0;"></span>
                                        <span class="color-option <?php echo ($module['background_color'] === 'blue') ? 'selected' : ''; ?>" 
                                              data-color="blue" data-name="蓝色" style="background-color: #D6E5FF;"></span>
                                        <span class="color-option <?php echo ($module['background_color'] === 'green') ? 'selected' : ''; ?>" 
                                              data-color="green" data-name="绿色" style="background-color: #D6FFE1;"></span>
                                        <span class="color-option <?php echo ($module['background_color'] === 'yellow') ? 'selected' : ''; ?>" 
                                              data-color="yellow" data-name="黄色" style="background-color: #FFEFD6;"></span>
                                        <span class="color-option <?php echo ($module['background_color'] === 'purple') ? 'selected' : ''; ?>" 
                                              data-color="purple" data-name="紫色" style="background-color: #E9D6FF;"></span>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">边框颜色</label>
                                    <input type="hidden" id="border_color" name="border_color" 
                                           value="<?php echo htmlspecialchars($module['border_color']); ?>">
                                    <div class="d-flex align-items-center mb-2">
                                        <div id="border-preview" class="color-preview" 
                                             style="background-color: <?php echo getColorCode($module['border_color']); ?>"></div>
                                        <span id="border-name"><?php echo getColorName($module['border_color']); ?></span>
                                    </div>
                                    <div>
                                        <span class="color-option border-option <?php echo ($module['border_color'] === 'pink') ? 'selected' : ''; ?>" 
                                              data-color="pink" data-name="粉红" style="background-color: #FFD6E0;"></span>
                                        <span class="color-option border-option <?php echo ($module['border_color'] === 'blue') ? 'selected' : ''; ?>" 
                                              data-color="blue" data-name="蓝色" style="background-color: #D6E5FF;"></span>
                                        <span class="color-option border-option <?php echo ($module['border_color'] === 'green') ? 'selected' : ''; ?>" 
                                              data-color="green" data-name="绿色" style="background-color: #D6FFE1;"></span>
                                        <span class="color-option border-option <?php echo ($module['border_color'] === 'yellow') ? 'selected' : ''; ?>" 
                                              data-color="yellow" data-name="黄色" style="background-color: #FFEFD6;"></span>
                                        <span class="color-option border-option <?php echo ($module['border_color'] === 'purple') ? 'selected' : ''; ?>" 
                                              data-color="purple" data-name="紫色" style="background-color: #E9D6FF;"></span>
                                    </div>
                                </div>
                                
                                <div class="mb-4 form-check">
                                    <input type="checkbox" class="form-check-input" id="is_active" name="is_active" 
                                           <?php echo $module['is_active'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="is_active">激活模块</label>
                                </div>
                                
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <a href="cognitive_modules.php" class="btn btn-outline-secondary me-md-2">取消</a>
                                    <button type="submit" class="btn btn-primary">保存模块</button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="sticky-top" style="top: 80px;">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0">模块预览</h5>
                                </div>
                                <div class="card-body">
                                    <div id="preview-card" class="preview-card" 
                                         style="background-color: <?php echo getColorCode($module['background_color']); ?>; 
                                                border: 2px solid <?php echo getColorCode($module['border_color']); ?>;">
                                        <div class="preview-header">
                                            <span id="preview-icon" class="preview-icon"><?php echo $module['icon']; ?></span>
                                            <span id="preview-title"><?php echo htmlspecialchars($module['module_name'] ?: '模块名称'); ?></span>
                                        </div>
                                        <p id="preview-description" class="text-muted">
                                            <?php echo nl2br(htmlspecialchars($module['description'] ?: '模块描述内容将显示在这里...')); ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">提示</h5>
                                </div>
                                <div class="card-body">
                                    <ul class="mb-0">
                                        <li>模块名称应简洁明了，适合3-4岁儿童</li>
                                        <li>描述内容会显示在模块卡片上</li>
                                        <li>图标可以帮助儿童快速识别模块内容</li>
                                        <li>选择适合内容主题的柔和马卡龙色系</li>
                                        <li>设置合理的显示顺序，重要内容靠前</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="/admin/js/bootstrap.bundle.min.js"></script>
    <script src="/admin/js/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            // 图标选择器
            $('#toggle-emoji-picker').click(function() {
                $('#emoji-picker').toggle();
            });
            
            $('.emoji-option').click(function() {
                const emoji = $(this).data('emoji');
                $('#icon').val(emoji);
                $('#selected-icon').text(emoji);
                $('#preview-icon').text(emoji);
                $('.emoji-option').removeClass('selected');
                $(this).addClass('selected');
            });
            
            // 背景颜色选择
            $('.color-option:not(.border-option)').click(function() {
                const color = $(this).data('color');
                const colorName = $(this).data('name');
                const colorCode = $(this).css('background-color');
                
                $('#background_color').val(color);
                $('#background-name').text(colorName);
                $('#background-preview').css('background-color', colorCode);
                $('#preview-card').css('background-color', colorCode);
                
                $('.color-option:not(.border-option)').removeClass('selected');
                $(this).addClass('selected');
            });
            
            // 边框颜色选择
            $('.border-option').click(function() {
                const color = $(this).data('color');
                const colorName = $(this).data('name');
                const colorCode = $(this).css('background-color');
                
                $('#border_color').val(color);
                $('#border-name').text(colorName);
                $('#border-preview').css('background-color', colorCode);
                $('#preview-card').css('border-color', colorCode);
                
                $('.border-option').removeClass('selected');
                $(this).addClass('selected');
            });
            
            // 实时预览功能
            $('#module_name').on('input', function() {
                $('#preview-title').text($(this).val() || '模块名称');
            });
            
            $('#description').on('input', function() {
                $('#preview-description').html(($(this).val() || '模块描述内容将显示在这里...').replace(/\n/g, '<br>'));
            });
        });
    </script>
</body>
</html>

<?php
/**
 * 根据颜色名称获取颜色代码
 */
function getColorCode($colorName) {
    $colorMap = [
        'pink' => '#FFD6E0',
        'blue' => '#D6E5FF',
        'green' => '#D6FFE1',
        'yellow' => '#FFEFD6',
        'purple' => '#E9D6FF'
    ];
    
    return isset($colorMap[$colorName]) ? $colorMap[$colorName] : '#FFD6E0';
}

/**
 * 根据颜色名称获取颜色中文名
 */
function getColorName($colorName) {
    $colorMap = [
        'pink' => '粉红',
        'blue' => '蓝色',
        'green' => '绿色',
        'yellow' => '黄色',
        'purple' => '紫色'
    ];
    
    return isset($colorMap[$colorName]) ? $colorMap[$colorName] : '粉红';
} 